package com.quan.bookmall.controller;

import com.quan.bookmall.dto.CartItemDTO;
import com.quan.bookmall.dto.response.ApiResponse;
import com.quan.bookmall.security.UserDetailsImpl;
import com.quan.bookmall.service.CartService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/cart")
@RequiredArgsConstructor
public class CartController {
    
    private final CartService cartService;
    
    @GetMapping
    public ResponseEntity<?> getCart(@AuthenticationPrincipal UserDetailsImpl userDetails) {
        List<CartItemDTO> cartItems = cartService.findByUserId(userDetails.getId());
        return ResponseEntity.ok(ApiResponse.success(cartItems));
    }
    
    @PostMapping
    public ResponseEntity<?> addToCart(
            @AuthenticationPrincipal UserDetailsImpl userDetails,
            @Valid @RequestBody CartItemDTO cartItemDTO) {
        
        CartItemDTO addedItem = cartService.addToCart(
                userDetails.getId(),
                cartItemDTO.getBookId(),
                cartItemDTO.getQuantity());
        
        return ResponseEntity.ok(ApiResponse.success(addedItem));
    }
    
    @PutMapping("/{bookId}")
    public ResponseEntity<?> updateCartItem(
            @AuthenticationPrincipal UserDetailsImpl userDetails,
            @PathVariable Long bookId,
            @RequestParam Integer quantity) {
        
        CartItemDTO updatedItem = cartService.updateQuantity(
                userDetails.getId(),
                bookId,
                quantity);
        
        return ResponseEntity.ok(ApiResponse.success(updatedItem));
    }
    
    @DeleteMapping("/{bookId}")
    public ResponseEntity<?> removeFromCart(
            @AuthenticationPrincipal UserDetailsImpl userDetails,
            @PathVariable Long bookId) {
        
        cartService.removeFromCart(userDetails.getId(), bookId);
        return ResponseEntity.ok(ApiResponse.success("商品已从购物车移除"));
    }
    
    @DeleteMapping
    public ResponseEntity<?> clearCart(@AuthenticationPrincipal UserDetailsImpl userDetails) {
        cartService.clearCart(userDetails.getId());
        return ResponseEntity.ok(ApiResponse.success("购物车已清空"));
    }
} 